<template>
  <div>
    <div id="container" style="width: 75%; height: 50vh;margin: auto; display: inline-block"></div>
    <div class="info" style="position: absolute; top: 80px; right: 205px; width: 200px; text-align: left; margin-left: 1000px" >
      <h4 id='status'></h4><hr>
      <p id='result'></p><hr>
    </div>
  </div>
</template>

<script>
import MapLoader from "@/components/Map/amap";
//信息窗口的内容
var content = [
    "<div>这是一个景点</div>"
];
export default {
  name: "Map",
  data(){
    return{
      lng: 0,
      lat: 0,
    }
  },
  methods:{

    getLocation: function () {
      alert(this.lng + " " + this.lat)
    },
    creatAMap: function () {
      let that = this;

      var map = new AMap.Map('container',{
        resizeEnable: true,
        zoom: 10,
        center: [116.480983, 40.0958]
      });

      map.setDefaultCursor('pointer');

      //创建右键菜单
      var contextMenu = new AMap.ContextMenu();
      //右键显示全国范围
      contextMenu.addItem("缩放至全国范围", function (e) {
        map.setZoomAndCenter(4, [108.946609, 34.262324]);
      }, 1);
      //右键添加Marker标记
      var contextMenuPosition = []
      contextMenu.addItem("添加标记", function (e) {
        map.remove([marker])
        marker = new AMap.Marker({
          icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: contextMenuPosition,
          offset: new AMap.Pixel(-26, -67)
        })
        map.add([marker])
      }, 2);

      //地图绑定鼠标右击事件——弹出右键菜单
      map.on('rightclick', function (e) {
        contextMenu.open(map, e.lnglat);
        contextMenuPosition = e.lnglat;
      });


      map.plugin(["AMap.Scale"],function(){
        var scale = new AMap.Scale({
          offset:new AMap.Pixel(10,30),
          position:'LB'
        });
        map.addControl(scale);
      });

      map.plugin(["AMap.ToolBar"],function(){
        //加载工具条
        var tool = new AMap.ToolBar({
          offset:new AMap.Pixel(10,30),
          position:'LT'
        });
        tool.show();
        map.addControl(tool);
      });

      // 获取访问用户的IP，实现IP定位
      AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：5s
          buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(25, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

        });
        map.addControl(geolocation);
        // todo 当用户点击其他位置更新经纬度， 重新定位时刷新不了经纬度
        geolocation.getCurrentPosition(function(status,result){
          if(status=='complete'){
            onComplete(result)
          }else{
            onError(result)
          }
        });
      });
      //解析定位结果
      function onComplete(data) {
        that.lng = data.position.lng;
        that.lat = data.position.lat;
        console.log(that.lng + " " + that.lat);

        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位结果：' + data.position);
        str.push('定位类别：' + data.location_type);
        if(data.accuracy){
          str.push('精度：' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');

      }
      //解析定位错误信息
      function onError(data) {
        alert("您的网络不佳，请稍后再试")
      }

      var marker = new AMap.Marker({
        map: map,
        icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [that.lng, that.lat],
      })

      //为地图注册click事件获取鼠标点击出的经纬度坐标
      map.on('click', function(e) {
        that.lng = e.lnglat.getLng()
        that.lat = e.lnglat.getLat()
        console.log("用户在[" + that.lng + "," + that.lat + "]点击了")
        map.remove([marker])
        marker = new AMap.Marker({
          icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [that.lng, that.lat],
          offset: new AMap.Pixel(-26, -67)
        })
        map.add([marker])
      });
    }
  },
  mounted() {
    let that = this
    MapLoader().then(AMap => {
      // that.map = new AMap.Map("container", {
      //   resizeEnable: true
      // });
      this.creatAMap()
    }, e => {
      console.log("加载失败")
    })
  }
}
</script>

<style  scoped>
html,body,#container{
  height:100%;
}
.info{
  width:26rem;
}

</style>